package com.base.social.signature.support;

import com.base.core.lang.StringUtils;
import com.base.social.signature.SignatureTemplate;

import java.util.Map;
import java.util.TreeMap;

/**
 * 生成京东宙斯平台的签名字符串
 * 宙斯签名规则过程如下:
 * 将所有请求参数按照字母先后顺序排列，例如将access_token,app_key,method,timestamp,v 排序为access_token,app_key,method,timestamp,v
 * 1.把所有参数名和参数值进行拼接，例如：access_tokenxxxapp_keyxxxmethodxxxxxxtimestampxxxxxxvx
 * 2.把appSecret夹在字符串的两端，例如：appSecret+XXXX+appSecret
 * 3.使用MD5进行加密，再转化成大写
 * link: http://open.jd.com/home/home#/doc/common?listId=890
 * link: https://github.com/pingjiang/jd-open-api-sdk-src/blob/master/src/main/java/com/jd/open/api/sdk/DefaultJdClient.java
 */
public class JdSignature extends SignatureTemplate {

    /**
     * 生成京东宙斯平台的签名字符串
     * 宙斯签名规则过程如下:
     * 将所有请求参数按照字母先后顺序排列，例如将access_token,app_key,method,timestamp,v 排序为access_token,app_key,method,timestamp,v
     * 1.把所有参数名和参数值进行拼接，例如：access_tokenxxxapp_keyxxxmethodxxxxxxtimestampxxxxxxvx
     * 2.把appSecret夹在字符串的两端，例如：appSecret+XXXX+appSecret
     * 3.使用MD5进行加密，再转化成大写
     * link: http://open.jd.com/home/home#/doc/common?listId=890
     * link: https://github.com/pingjiang/jd-open-api-sdk-src/blob/master/src/main/java/com/jd/open/api/sdk/DefaultJdClient.java
     *
     * @param params    签名参数
     * @return 签名后的字符串
     */
    @Override
    public String generateSignature(Map<String, Object> params) {
        Map<String, Object> treeMap = new TreeMap<>(params);
        StringBuilder signBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
            String name = entry.getKey();
            String value = String.valueOf(entry.getValue());
            if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(value)) {
                signBuilder.append(name).append(value);
            }
        }
        return md5(signBuilder.toString()).toUpperCase();
    }
}
